package com.example.lizhanqi.livevideo.ui.activity;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.example.lizhanqi.livevideo.R;
import com.example.lizhanqi.livevideo.ui.fragment.HomeFragment;
import com.example.lizhanqi.livevideo.ui.fragment.MyProfileFragment;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Button btn_main_home;
    private Button btn_main_live;
    private Button btn_main_me;
    private RelativeLayout main_bottoms;
    private RelativeLayout fragment_container;
    private int currentIndex=0;
    private int index=0;
    private Fragment[] fragments;
    private Button[] buttons;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fragments = new Fragment[] { new HomeFragment(), new MyProfileFragment()};
        // 添加显示第一个fragment
        getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, fragments[index]).commit();
        initView();
    }
    private void initView() {
        btn_main_home = (Button) findViewById(R.id.btn_main_home);
        btn_main_live = (Button) findViewById(R.id.btn_main_live);
        btn_main_me = (Button) findViewById(R.id.btn_main_me);
        main_bottoms = (RelativeLayout) findViewById(R.id.main_bottoms);
        buttons = new Button[]{btn_main_home,btn_main_me};
        buttons[index].setSelected(true);
        fragment_container = (RelativeLayout) findViewById(R.id.fragment_container);
        btn_main_home.setOnClickListener(this);
        btn_main_live.setOnClickListener(this);
        btn_main_me.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_main_home:
                index = 0;
                break;
            case R.id.btn_main_live:
                Toast.makeText(MainActivity.this, "直播页面", Toast.LENGTH_SHORT).show();
                break;
            case R.id.btn_main_me:
                index = 1;
                break;
        }
        if (currentIndex != index) {
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            fragmentTransaction.hide(fragments[currentIndex]);
            buttons[currentIndex].setSelected(false);
            if (!fragments[index].isAdded()) {
                fragmentTransaction.add(R.id.fragment_container, fragments[index]);
            }
            fragmentTransaction.show(fragments[index]).commit();
        }
        // 把当前tab设为选中状态
        buttons[index].setSelected(true);
        currentIndex = index;
    }
}
